
package com.farsunset.ichat.cim.handler;

import org.apache.log4j.Logger;

import com.farsunset.cim.nio.constant.CIMConstant;
import com.farsunset.cim.nio.handler.CIMRequestHandler;
import com.farsunset.cim.nio.mutual.ReplyBody;
import com.farsunset.cim.nio.mutual.SentBody;
import com.farsunset.cim.nio.session.CIMSession;
import com.farsunset.cim.nio.session.SessionManager;
import com.farsunset.ichat.common.util.ContextHolder;
import com.kuaigou.cim.util.AESEncodeUtil;

/**
 * 客户端心跳实现
 * 
 * @author
 */
public class HeartbeatHandler implements CIMRequestHandler {

	protected final Logger logger = Logger.getLogger(HeartbeatHandler.class);

	public ReplyBody process(CIMSession session, SentBody message) {
		ReplyBody reply = new ReplyBody();
		try {
			reply.setKey(CIMConstant.RequestKey.CLIENT_HEARTBEAT);
			String account = message.get("account");
			
			logger.error("account=" + account);
			
			String verificationCode = message.get("verificationCode");
			if (verificationCode == null
					|| !account.equals(AESEncodeUtil.decrypt(verificationCode, AESEncodeUtil.key))) {
				reply.setCode(CIMConstant.ReturnCode.CODE_403);
				return reply;
			}
			reply.setCode(CIMConstant.ReturnCode.CODE_200);
			long htime = System.currentTimeMillis();
			session.setHeartbeat(htime);
			SessionManager sessionManager = ContextHolder.getBean(SessionManager.class);

			sessionManager.addSession(account, session);
		} catch (Exception e) {
			reply.setCode(CIMConstant.ReturnCode.CODE_500);
		}
		return reply;
	}
}